#include "Semaphore.h"

Semaphore::Semaphore(int value)
{
	S1=new Mutex();
	S2=new Mutex();
	m_wake=0;
	m_value=value;
	if (value==0) S2->lock((Thread*)NULL);
}

Semaphore::~Semaphore()
{
	delete S1;
	delete S2;
}

void Semaphore::setValue(int value)
{
m_value=value;
}

int Semaphore::getValue()
{
return m_value;
}

void Semaphore::down()
{
	S1->lock(self());
	m_value--;
	if (m_value < 0){
		S1->unlock();
		S2->lock(self());
		S1->lock(self());
		m_wake--;
		if (m_wake>0)
			S2->unlock();
	}
	S1->unlock();
}

void Semaphore::up()
{
	S1->lock(self());
	m_value++;
	if (m_value <= 0){
		m_wake++;
		if (m_wake==1) S2->unlock();}
	S1->unlock();
};

